<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    public function index(){
        return view('User.register');
    }
    public function register(Request $request){
//        dd();
        $this->validate($request,[
            'name'=>'bail|required|min:3|max:10|unique:users,name',
            'email'=>'bail|required|email|unique:users,email',
            'password'=>'bail|required|min:6|max:18|confirmed'
        ]);
        $info=$request->all();
        $info['password']=bcrypt($info['password']);

        // 构建token激活码
        $info['token']=md5($info['name'].$info['password'].time());
        $info['token_exptime']=time()+60*60*24;

        //批量保存到db
        User::create($info);

        //发送邮件
        $to=$info['email'];//邮件地址
        $subject='欢迎注册';//邮件标题
        \Mail::send('emails.active',['token'=>$info['token']],function ($message) use($to,$subject){
            $message->to($to)->subject($subject);
        });
        return redirect('login')->with('message','注册成功，请到邮箱激活');
    }
    public function active($code){
        $user=User::where('token',$code)->first();
        if($user->token_exptime>time()){
            $user->status=1;
            $user->save();
            return redirect('article')->with('message','激活成功');
        }else{
            return redirect('login')->with('message','激活码已过期,请登录后重新发送激活邮件');
        }
    }
}
